package com.huanying.goodjob.advertisment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.huanying.framework.BaseController;
import com.huanying.framework.PageBean;
import com.huanying.goodjob.community.Area;
import com.huanying.goodjob.community.CommunityService;

@Controller

public class AdvertismentController extends BaseController{
	private static Logger logger = Logger.getLogger(AdvertismentController.class);
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	@Autowired
	private AdvertismentService adService;
	@Autowired
	private CommunityService communityService;
	//后台查询广告
	@RequestMapping("/show_add_advertisment.do")
	public String show_add_advertisement(String title,String content,String province, String city, String county,String page_num,Model model){
		PageBean pageBean = null;
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("title",title);
		map.put("content",content);
		map.put("province", province);
		map.put("city", city);
		map.put("county", county);
		if (page_num == null) {
			page_num = "1";
		}
		try {
			pageBean = adService.search_ad(map, super.getPageSize(), Integer.valueOf(page_num));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("查询广告失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("查询广告失败", e);
		}
		model.addAttribute("title",title);
		model.addAttribute("content",content);
		model.addAttribute("ads",pageBean.getList());
		model.addAttribute("page", pageBean);
		return "/advertisment/add_advertisment";
	}
	//后台添加广告
	@RequestMapping("/add_advertisment.do")
	@ResponseBody
	public Map<String,Object> add_advertisment(String title,String content,@RequestParam("file") MultipartFile image_01,String status,String id,String province_code, String city_code, String county_code){
		Map<String,Object> map=new HashMap<String,Object>();
		String file_name = "";
		String filePath =null;
		Advertisment advertisment=new Advertisment();
		Area province;
		try {
			if(province_code!=null && province_code!="")
			{
			province = communityService.getbyCode(province_code);
			advertisment.setProvince(province);
			}
			if(city_code!=null && city_code!="")
			{
			Area city = communityService.getbyCode(city_code);
			advertisment.setCity(city);
			}
			if(county_code!=null && county_code!="")
			{
			Area county = communityService.getbyCode(county_code);
			advertisment.setCounty(county);
			}
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			logger.error("获取区域失败", e2);
		}

		advertisment.setTitle(title);
		advertisment.setContent(content);
		if (!image_01.isEmpty()) {
			// 获得上传时的文件名
			String temp_name = image_01.getOriginalFilename();
			String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
			file_name = UUID.randomUUID().toString() + postfix;
			filePath =super.getSession().getServletContext().getRealPath("")+ File.separator+ "fileUpload"+ File.separator+"ad"+File.separator + file_name;
			logger.info(filePath);
			try {	
		//		filePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload"
			//			+ File.separator+"ad"+File.separator + file_name;		
				image_01.transferTo(new File(filePath));	
				logger.info("You successfully uploaded");
			} catch (Exception e) {
				logger.error("You failed to upload", e);
				map.put("flag","3");
				return map;
			}
			
			String realfliePath="fileUpload"+ File.separator+"ad"+File.separator + file_name;
			advertisment.setImg_url(realfliePath);
		} else {
			logger.info("You failed to upload because the file was empty.");
		}
		if(Integer.parseInt(id)==0)
		{
			advertisment.setStatus(1);
			try {
				adService.add_ad(advertisment);
				map.put("flag","1");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if(filePath!=null)
				{
					new File(filePath).delete();
				}
				map.put("flag", "0");
				logger.error("添加广告失败", e);
			
			}
		}
		else{
			advertisment.setId(Integer.parseInt(id));
			advertisment.setStatus(Integer.parseInt(status));
			try {
				if((adService.get_ad(advertisment.getId())).getImg_url()!=null && advertisment.getImg_url()==null)
				{
				advertisment.setImg_url((adService.get_ad(advertisment.getId())).getImg_url());
				}
				} catch (Exception e1) {
				// TODO Auto-generated catch block
				
				logger.error("获取单个广告失败", e1);
			}
			try {
				adService.update_ad(advertisment);
				map.put("flag", "1");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if(filePath!=null)
				{
					new File(filePath).delete();
				}
				logger.error("修改广告失败", e);
				map.put("flag", "0");
			}
		}
		
		return map;
	}
	//修改广告信息
	@RequestMapping("/delete_advertisment.do")
	@ResponseBody
	public Map<String,Object> delete_advertisment(int id){
		Map<String,Object> map=new HashMap<String,Object>();
		try {
			adService.delete_ad(id);
			map.put("flag","1");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("删除失败", e);
			map.put("flag","0");
		}
		
		return map;
	}
	@RequestMapping("/get_advertisment.do")
	@ResponseBody
	public Map<String,Object> get_advertisment(String id){
		Map<String,Object> map=new HashMap<String,Object>();
		Advertisment ad;
		try {
			ad=adService.get_ad(Integer.parseInt(id));
			map.put("flag","1");
			map.put("ad",ad);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个广告失败", e);
			map.put("flag","0");
		}
		
		return map;
	}
	
	
	//前台获取广告
	@CrossOrigin
	@RequestMapping(value="/front_get_advertisment.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String front_get_advertisment(String jsoncallback,String province_code,String city_code,String county_code){
		List<Advertisment> ads=new ArrayList<Advertisment>();
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> map1=new HashMap<String,Object>();
		map1.put("province_code",province_code);
		map1.put("city_code",city_code);
		map1.put("county_code",county_code);
		try {
			ads=adService.front_get_advertisment(map1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("前台获取广告失败", e);
		}
		map.put("list",ads);
		Gson gson=new Gson();
		String json="";
		json=gson.toJson(map);
		return jsoncallback+"("+json+")";
		
	}
	//前台获取单个广告
	@RequestMapping(value="/front_get_byadvertismentId.do", method=RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String front_get_byadvertismentId(String id,String jsoncallback)
	{
		Map<String,Object> map=new HashMap<String,Object>();
		Advertisment ad;
		try {
			ad=adService.get_ad(Integer.parseInt(id));
			map.put("list",ad);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("前台获取单个广告失败", e);
			map.put("flag","0");
		}
		
		Gson gson=new Gson();
		String json="";
		json=gson.toJson(map);
		return jsoncallback+"("+json+")";
		
	}
}
